#! /bin/bash
#
# debian/repack
# Part of the Debian package ‘inform6-library’.
#
# Copyright © 2010–2016 Ben Finney <ben+debian@benfinney.id.au>
#
# This is free software; you may copy, modify, and/or distribute this
# work under the terms of the GNU General Public License as published
# by the Free Software Foundation; version 3 of that License or later.
# No warranty expressed or implied.
# See the file ‘/usr/share/common-licenses/GPL-3’ for details.

# Convert the pristine upstream source to the Debian upstream source.
#
# This program is designed for use with the ‘uscan(1)’ tool, as the
# “action” parameter for the ‘debian/watch’ configuration file.

set -o errexit
set -o errtrace
set -o pipefail
set -o nounset

program_dir="$(dirname "$(realpath --strip "$0")")"
source "${program_dir}"/source_package_build.bash

function usage() {
    local progname=$(basename $0)
    printf "$progname --upstream-version VERSION FILENAME\n"
}

if [ $# -ne 3 ] ; then
    usage
    exit 1
fi

upstream_version="$2"
downloaded_file="$3"

target_filename="${upstream_tarball_basename}.tar.gz"
target_working_file="${working_dir}/${target_filename}"
target_file="$(dirname "${downloaded_file}")/${target_filename}"

repack_dir="${working_dir}/${upstream_dirname}"

printf "Unpacking pristine upstream source ‘%s’:\n" "${downloaded_file}"

extract_tarball_to_working_dir "${downloaded_file}"

upstream_source_dirname=$(ls -1 "${working_dir}")
upstream_source_dir="${working_dir}/${upstream_source_dirname}"

printf "Repackaging upstream source from ‘%s’ to ‘%s’:\n" \
       "${upstream_source_dir}" "${repack_dir}"

mv "${upstream_source_dir}" "${repack_dir}"

printf "Removing non-source files:\n"

nonsource_files=(
        # Generated files without corresponding source form.
        infglk.h

        )

for f in "${nonsource_files[@]}" ; do
    rm -f -v "${repack_dir}"/$f
done

printf "Rebuilding DFSG-free upstream source tarball:\n"

archive_working_dir_to_tarball "${upstream_dirname}" "${target_working_file}"

printf "Moving completed upstream tarball to ‘%s’:\n" "${target_file}"

rm -v "${downloaded_file}"
mv "${target_working_file}" "${target_file}"

printf "Done.\n"


# Local variables:
# coding: utf-8
# mode: shell-script
# indent-tabs-mode: nil
# End:
# vim: fileencoding=utf-8 filetype=bash expandtab :
